<template>
  <bs-dialog :title="$t('角色编辑')" :visible.sync="editor" size="default">
    <template slot="main">
      <div class="dialog-content">
        <el-form
          ref="editorFormRef"
          :inline="true"
          :model="editorForm"
          class="edit-actor-form"
          :rules="formRules"
          :show-message="false"
          :hide-required-asterisk="true"
          :status-icon="false"
        >
          <el-form-item :label="$t('角色名称')" prop="name">
            <el-input
              v-model="editorForm.name"
              autocomplete="off"
              :show-word-limit="false"
              maxlength="20"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('发布级别')" class="dialog-form-itemlevel">
            <el-radio-group v-model="editorForm.radio">
              <el-radio
                v-for="item in levelData"
                :key="item.id"
                :label="item.id"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-form>
        <custom-transfer
          class="trans-table"
          :dataleft.sync="authedData"
          :dataright.sync="unAuthData"
          :columns="columns"
        ></custom-transfer>
      </div>
    </template>
    <template slot="footer">
      <el-button type="primary" size="small" @click="onHandleConfirm">{{ $t('确定') }}</el-button>
      <el-button @click="onHandleClose" size="small">{{ $t('取消') }}</el-button>
  </template>
  </bs-dialog>
</template>
<script>
import CustomTransfer from './CustomTransfer'
import { deepClone } from '@/utils/index'
export default {
  name: 'ActorEditDialog',
  components: { CustomTransfer },
  data() {
    const headerContextMenus = {
      width: '120px',
      items: ['sortUp', 'sortDown', 'line', 'cols'],
    }
    return {
      activeName: 'first',
      editor: false,
      editorForm: {
        name: '',
        id: 0,
        radio: 0,
      },
      defaultradio: 0,
      levelData: [
        { label: this.$t('优先级0'), id: 0 },
        { label: this.$t('优先级1'), id: 1 },
        { label: this.$t('优先级2'), id: 2 },
      ],
      formRules: {
        name: [
          {
            required: true,
            message: this.$t('请输入名称'),
            trigger: 'blur',
          },
          { min: 1, max: 20, message: this.$t('长度在 1 到 20 个字符') },
          {
            pattern: /^[A-Za-z\u4e00-\u9fa5]+$/,
            message: this.$t('角色名只能为中英文'),
          },
        ],
      },
      authedData: [],
      unAuthData: [],
      columns: [
        {
          label: this.$t('权限'),
          prop: 'resourceName',
          sortable: false,
          align: 'center',
          width: 130,
          // headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
        {
          label: this.$t('分类'),
          prop: 'parentName',
          sortable: false,
          width: 140,
          align: 'center',
          // headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
        {
          label: this.$t('操作'),
          prop: 'operation',
          sortable: false,
          align: 'center',
          // headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
      ],
      input: '',
      showContextMenu: false,
      dropdownList: [
        { visible: false, value: '1', label: this.$t('升序') },
        { visible: false, value: '2', label: this.$t('降序') },
      ],
      isAdd: true,
    }
  },
  created() {
    this.$eventBus.$on('addDialogShow', this.show)
  },
  beforeDestroy() {
    this.$eventBus.$off('addDialogShow')
  },

  methods: {
    // 显示
    show(userData, isadd) {
      //每次弹窗先清空本地数组数据
      console.log('show add =', userData)
      this.isAdd = isadd
      this.authedData = []
      this.unAuthData = []
      if (!this.isAdd) {
        this.authedData = deepClone(sortByKey(userData.authed, 'code'))
        this.editorForm.name = userData.name
        this.editorForm.radio = userData.programPublishLevel
        this.editorForm.id = userData.id
      }
      this.unAuthData = deepClone(sortByKey(userData.unauthed, 'code'))

      this.editor = true
    },
    onHandleConfirm() {
      this.$refs.editorFormRef.clearValidate()
      this.$refs.editorFormRef.validate(async (valid) => {
        if (valid) {
          this.updateActor()
        } else {
          let index = 0
          this.$refs.editorFormRef.fields.forEach((field) => {
            if (field.validateMessage) {
              if (index === 0) {
                console.log(field.validateMessage)
                this.$message.error(field.validateMessage)
                this.validateMsg = []
              }
              index++
            }
          })
          return
        }
      })
    },
    updateActor() {
      var actorRow = {
        name: this.editorForm.name,
        authed: this.authedData,
      }
      const permissionCodes = []
      this.authedData.forEach((element) => {
        permissionCodes.push(element.code)
      })
      if (this.isAdd) {
        console.log('this.editorForm.level--------', this.editorForm.radio)
        if (typeof this.editorForm.radio === 'undefined') {
          this.$message.error(this.$t('未选择发布等级'))
          return
        }
        let params = {
          programPublishLevel: this.editorForm.radio,
          name: this.editorForm.name,
          permissionCodes: permissionCodes,
        }
        this.$store.dispatch('system/saveRole', params).then((res) => {
          //更新列表
          this.editor = false
          this.resetForm()
          this.$eventBus.$emit('refreshActorlist', false)
          this.$success('add')
        })
      } else {
        let updateparams = {
          id: this.editorForm.id,
          programPublishLevel: this.editorForm.radio,
          name: this.editorForm.name,
          permissionCodes: permissionCodes,
        }
        this.$store.dispatch('system/modifyRole', updateparams).then((res) => {
          //更新列表
          this.editor = false
          this.resetForm()
          this.$eventBus.$emit('refreshActorlist', false)
          this.$success('upd')
        })
        //TODO 提交更新接口  根据返回值处理 失败：提示？成功：通知list刷新
      }
    },
    onHandleClose() {
      this.$refs.editorFormRef.clearValidate()
      this.editor = false
      this.resetForm()

      console.log('onHandleClose')
    },
    resetForm() {
      this.editorForm = {
        name: '',
        id: 0,
        radio: 0,
      }
    },
  },
}
// 数组对象方法排序：
function sortByKey(array, key) {
  return array.sort(function (a, b) {
    var x = a[key]
    var y = b[key]
    return x < y ? -1 : x < y ? 1 : 0
  })
}
function isEmpty(obj) {
  if (obj.match(/^\s*$/)) {
    return true
  } else {
    return false
  }
}
function valitName(name) {
  var reg = /^[\u0391-\uFFE5A-Za-z]+$/
  if (reg.test(name)) {
    return true
  } else {
    return false
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
 ::v-deep .el-dialog {
  width: 1000px !important;
  height: 650px !important;
}

.dialog-content {
  margin-top: 10px;
}
.dialog-form-itemlevel {
  margin-left: 30px;
}
.el-radio-group {
  padding-left: 30px;
}
.el-form-item {
  margin-bottom: 10px !important;
}
.el-input {
  width: 420px;
}
::v-deep .el-dialog__footer {
  border-top: 0 !important;
}
::v-deep .el-button--small{width:45px;}
::v-deep .transfer-guide{flex-direction: inherit !important;}

</style>